<?php

declare(strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use think\facade\Db;
use think\response\Json;
use addons\WeChatMini\facade\WeChatMini;

class Express extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Express';

    //验证器
    protected string $validate = 'Express';

    public function index(): string
    {
        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barDemo,140')
            ->addRightButtons(['edit' => ['size' => '50%'], 'delete'])
            ->addTopButtons([
                'add' => ['size' => '50%'],
                'sync_info' => [
                    'title' => '同步快递物流',
                    'event' => '_submitTop',
                    'url' => url('express/syncInfo')->build()
                ],
                'deleteAll'
            ])
            ->addSearch([['title', '填写快递名称', 'input,Like']])
            ->fetch();
    }
    public function syncInfo()
    {

        try {
            $data = ['appid'=>config('wechat.appid')];
            $res = WeChatMini::isTradeManaged($data);
            // $list = WeChatMini::getCompanyList();
            print('<pre>');print_r($res);die;
            Db::execute("truncate table express");
            foreach ($list['delivery_list'] as $k => $v) {
                $data['title'] = $v['delivery_name'];
                $data['code'] = $v['delivery_id'];
                $data['description'] = $v['delivery_name'];
                $data['sort'] = ($k+1);
                $this->model::create($data);
            }
            return json(['code' => 1, 'msg' => '同步成功！']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
}
